﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Net;
using System.Management;
using Microsoft.WindowsAzure.ServiceRuntime;
using System.IO;

namespace WordPressShared
{
    public class SMBService : ISMBService
    {
        public static string GetUrlFormat(IPEndPoint Ip)
        {
            return string.Format("net.tcp://{0}/SMBService", Ip);
        }

        public static ISMBService GetAProxy(string Url)
        {
            NetTcpBinding binding = new NetTcpBinding(SecurityMode.None);
            EndpointAddress endpointAddress = new EndpointAddress(Url);

            return new ChannelFactory<ISMBService>
                (binding, endpointAddress).CreateChannel();
        }


        public static bool LoadingSMB = false;
        /// <summary>
        /// Indica si el Worker role actual está montando SMB
        /// </summary>
        /// <returns></returns>
        public bool IsLoadingSMB()
        {
            return LoadingSMB;
        }

        /// <summary>
        /// Comprueba si el servicio SMB está iniciado en un Worker Role
        /// </summary>
        /// <returns></returns>
        public bool IsSMBEnabled()
        {
            string MessageLog = "";
            try
            {
                List<ManagementObject> sharedFolders = GetSharedFolders();
                if (sharedFolders.Count < 1)
                    return false;

                foreach (ManagementObject shared in sharedFolders)
                {
                    if (shared["Name"].ToString().Equals("sharerw"))
                    {
                        var xDrive = Directory.GetLogicalDrives().Where(d => d.Contains(shared["Path"].ToString()));
                        if (xDrive != null)
                        {
                            try
                            {
                                Directory.GetFiles(shared["Path"].ToString());
                                return true;
                            }
                            catch
                            {
                                return false;
                            }
                        }
                        return false;
                    }
                }
                return false;
            }
            catch(Exception ex)
            {
                MessageLog += "Exception: " + ex.Message;
                return false;
            }
           
        }


        private static List<ManagementObject> GetSharedFolders()
        {
            List<ManagementObject> sharedFolders = new List<ManagementObject>();

            try
            {
                // Object to query the WMI Win32_Share API for shared files...
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from win32_share");
                ManagementClass mc = new ManagementClass("Win32_Share"); //for local shares
                foreach (ManagementObject share in searcher.Get())
                {

                    string type = share["Type"].ToString();

                    if (type == "0") // 0 = DiskDrive (1 = Print Queue, 2 = Device, 3 = IPH)
                    {
                        sharedFolders.Add(share);
                    }
                }


            }
            catch
            {
            }

            return sharedFolders;
        }

        /// <summary>
        /// Solo WebRol
        /// Comprueba si se ha configurado la unidad de red en el Web Rol
        /// </summary>
        /// <returns></returns>
        public bool IsNetWorkDriveSMBConfigured()
        {
            try
            {
                string RealPath = RoleEnvironment.GetConfigurationSettingValue("localPath");

                // verificamos la conexión con Azure Drive mediante SMB
                // Comprobamos que existe la unidad de red al servidor de SMB
                var xDrive = Directory.GetLogicalDrives().Where(d => d.Contains(RealPath));
                if (xDrive == null)
                {
                    return false;
                }
                else
                {
                    // Verificamos que la carpeta está en línea
                    try
                    {
                        Directory.GetFiles(RealPath);
                        return true;
                    }
                    catch
                    {
                        return false;
                    }
                }
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Solo WebRol
        /// Reconecta los WebRoles a SMB
        /// </summary>
        public bool ReconnectNetworkDriveSMB(string SMBMachineIP)
        {
            try
            {
                return RoleStartupUtils.MapNetworkDrive(false, SMBMachineIP, RoleEnvironment.GetConfigurationSettingValue("localPath"),
                                                RoleEnvironment.GetConfigurationSettingValue("shareName"),
                                                RoleEnvironment.GetConfigurationSettingValue("fileshareUserName"),
                                                RoleEnvironment.GetConfigurationSettingValue("fileshareUserPassword"));
            }
            catch
            {
                return false;
            }
        }


    }
}
